#!encoding: utf-8

from .models import Minion, MinionDetail, Job
from .saltapi import salt
from django.utils import timezone

def jobPersist(jid, cmd, tgt = '*'):
    '''
    查询job id对应的返回结果, 构造并存入数据库
    '''
    print(jid)
    print(cmd)
    params = {
        'client':'runner', 
        'fun':'jobs.lookup_jid', 
        'jid': jid,
        'missing': True,
    }
    result = salt.postRequest(params)['return'][0]
    for item in result.keys():
        job = {}
        if result[item] == u'Minion did not return':
            job['status'] = 2
        else:
            job['status'] = 1

        exists = Minion.objects.filter(key = item).exists()
        if not exists:
            print('minion不存在')
            continue

        minion = Minion.objects.get(key = item)
        job['minion_id'] = minion
        job['jid'] = jid
        job['cmd'] = cmd
        job['target'] = tgt
        job['result'] = result[item]
        try:
            Job.objects.create(**job)
        except Exception as err:
            print(err)
